package com.FH.applyFrom.advanceForm;

import com.FH.applyForm.officeServies.advance.AdvancePullDTO;
import com.FH.applyForm.officeServies.advance.AdvanceResource;
import com.FH.applyForm.officeServies.advance_type.AdvanceTypeResource;
import com.FH.applyForm.officeServies.expenform_firsttype.ExpenformResource;
import com.FH.organization.operator_log.OperatorLogPullDTO;
import com.FH.organization.operator_log.OperatorLogResource;
import com.FH.organization.suggestion.SuggestionResource;
import com.FH.organization.work_flow.WorkFlowPullDTO;
import com.FH.organization.work_flow.WorkFlowResource;
import com.FH.util.AccessDB;
import com.FH.util.ResultDTO;
import com.FH.util.warnSrc;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;

import javax.ejb.Stateless;
import javax.inject.Inject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2016/7/15.
 *预支费用申请单实现类
 */

@Stateless
public class AdvanceFormDAOImpl extends AccessDB implements AdvanceFormDAO{


    @Inject
    OperatorLogResource operatorLogResource;

    @Inject
    WorkFlowResource workFlowResource;

    @Inject
    AdvanceFormResource advanceFormResource;

    @Inject
    AdvanceTypeResource advanceTypeResource;

    @Inject
    AdvanceResource advanceResource;
    @Inject
    ExpenformResource expenformfirstResource;
    @Inject
    SuggestionResource suggestionResource;

    @Override
    public ResultDTO getAdvanceFormInfo(String search, String page, String size) {

        ResultDTO resultDTO = new ResultDTO();

        try {

            JSONObject json_search = new JSONObject(search);
            String sql_where = "";//条件搜索sql
            String sql_page ="";//分页sql

            Integer page_ok = Integer.parseInt(page);
            Integer size_ok = Integer.parseInt(size);
            if(page.equals("1")){
                sql_page = " limit 0,"+size+"";
            }else{
                sql_page = " limit "+((page_ok-1)*size_ok)+","+size+"";
            }

//            if(json_search.has("advance_form_id")){ //休假申请单主键id
//                sql_where += " AND advance_form_id ="+json_search.getString("advance_form_id");
//            }

            if(json_search.has("isverify")){
                sql_where += " AND isverify ='" + json_search.getString("isverify")+"'";
            }
//            else{
//                sql_where += " AND (isverify IS NULL OR isverify=0)";
//            }

            if(json_search.has("member_id")){ //用户id
               // sql_where += " AND member_id ="+json_search.getString("member_id");
                sql_where += " AND member_id ='" + json_search.getString("member_id")+"'";
            }

            if (json_search.has("advance_form_id")){
                sql_where += " AND advance_form_id ='" + json_search.getString("advance_form_id")+"'";
            }

            String sqlexit = "select count(1) from advance_form  where 1=1 ";
            String sqlexit_ok = sqlexit + sql_where +sql_page;

            String existName = getReportingToOne(sqlexit + sql_where);//查询此数据是否存在

            List<String []> seresult = new ArrayList<String []>();

            List<AdvanceFormShowDTO> result = new ArrayList<AdvanceFormShowDTO>();

            if(!existName.equals("0")){
                String sql ="SELECT advance_form_id,advance_form_reason,advance_form_number,advance_form_time,member_id,isverify,fail_resource,advance_from_firsttype_id FROM advance_form WHERE 1=1 "
                        +sql_where+" ORDER BY advance_form_time DESC"+sql_page;

                seresult = this.getReportingTo(sql);
            }
            if(seresult.size()>0){
                //如果查询成功，构建返回对象
                for (int i=0;i<seresult.size();i++){
                    AdvanceFormShowDTO advanceFormShowDTO = new AdvanceFormShowDTO();
                    advanceFormShowDTO.setAdvance_form_id(seresult.get(i)[1]);
                    advanceFormShowDTO.setAdvance_form_reason(seresult.get(i)[2]);
                    advanceFormShowDTO.setAdvance_form_number(seresult.get(i)[3]);
                    advanceFormShowDTO.setAdvance_form_time(seresult.get(i)[4]);
                    advanceFormShowDTO.setMember_id(seresult.get(i)[5]);
                    advanceFormShowDTO.setIsverify(seresult.get(i)[6]);
                    advanceFormShowDTO.setFail_resource(seresult.get(i)[7]);
                    advanceFormShowDTO.setAdvance_from_firsttype_id(seresult.get(i)[8]);
                    ResultDTO worklist=null,userlist=null,firsttype=null,suggestion=null;
                    if(json_search.has("isverify")){
                        String state=json_search.getString("isverify");
                        worklist=workFlowResource.getWorkFlowInfo("{work_flow_formid:"+seresult.get(i)[1]+",work_flow_state:"+state+"}","1","20");
                    }else{
                        worklist=workFlowResource.getWorkFlowInfo("{work_flow_formid:"+seresult.get(i)[1]+"}","1","20");
                    }
                    advanceFormShowDTO.setWs(worklist.getValues());

                    userlist=advanceResource.getOfficeNameInfo("{advance_form_id:"+seresult.get(i)[1]+"}","1","10000");
                    advanceFormShowDTO.setQq(userlist.getValues());

                    if(seresult.get(i)[8] != null && ! seresult.get(i)[8].equals("")){

                        firsttype=expenformfirstResource.getExpenformTypeInfo("{advancetype_id:" + seresult.get(i)[8] + "}", "1", "100");
                        advanceFormShowDTO.setExpenformShowDTOList(firsttype.getValues());
                    }
                    if(seresult.get(i)[1] != null && ! seresult.get(i)[1].equals("")){

                        suggestion=suggestionResource.getSuggestionInfo("{form_id:" + seresult.get(i)[1] + "}", "1", "100");
                        advanceFormShowDTO.setSuggestionShowDTOs(suggestion.getValues());
                    }

                    result.add(advanceFormShowDTO);
                }


                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.get_success);
            }else{
                resultDTO.setStatus("90001");
                resultDTO.setDescritpion(warnSrc.get_fail);
            }

            resultDTO.setStr(result.size()+"");
            resultDTO.setValues(result);

        }catch (Exception e){
            e.printStackTrace();
        }

        return resultDTO;
    }

    @Override
    public ResultDTO addAdvanceFormInfo(AdvanceFormPullDTO advanceFormPullDTO) {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//日期格式化

        String advance_form_id = advanceFormPullDTO.getAdvance_form_id();
        String advance_form_reason = advanceFormPullDTO.getAdvance_form_reason();
        String advance_form_number = advanceFormPullDTO.getAdvance_form_number();

        String advance_form_time = df.format(new Date());//申请时间
        String member_id = advanceFormPullDTO.getMember_id();

        String uuid = UUID.randomUUID().toString().trim().replaceAll("-", "");

        int resultls=0;
        String existName = "";
        /**
         * 判断advance_form_id是否为空
         *
         *       不为空的情况下执行修改方法，
         *
         *       为空得情况下，执行执行此方法
         */

        //构建返回对象
        ResultDTO resultDTO = new ResultDTO();


         if(advance_form_id!=null&&!advance_form_id.equals("")){

             String sql = "select count(1) from advance_form where advance_form_id='"+advanceFormPullDTO.getAdvance_form_id()+"'";

             existName=getReportingToOne(sql);

             if(!existName.equals("0")) {
                 return advanceFormResource.updateAdvanceFormInfo(advanceFormPullDTO);
             }
        }

            String advanceForm_insert = "";
            //构建插入sql
            advanceForm_insert +="INSERT  INTO advance_form(advance_form_id,advance_form_reason,advance_form_time,member_id,isverify,fail_resource,advance_from_firsttype_id)" +
                    " VALUES('"+uuid+"','"+advance_form_reason+"','"+
                    advance_form_time+"','"+member_id+"','0','"+" "+"','"+advanceFormPullDTO.getAdvance_from_firsttype_id()+"')";

            //插入业务表
            resultls =  addReportingTo(advanceForm_insert);

            if(resultls != 0){
                resultDTO.setStr(uuid);
                resultDTO.setStatus("90000");
                resultDTO.setDescritpion(warnSrc.add_success);

                /**
                 * JSON解析集合
                 */
                if(null!=advanceFormPullDTO.getAdvancetype()&& !"".equals(advanceFormPullDTO.getAdvancetype())){
                    String advancetype=advanceFormPullDTO.getAdvancetype();
                    try {
                        JSONArray array=new JSONArray(advancetype);
                        if(array!=null&&array.length()>0){
                            List<AdvanceFormPullDTO> result = new ArrayList<AdvanceFormPullDTO>();
                            for(int i = 0; i < array.length(); i++){
                                JSONObject jsonObject=array.getJSONObject(i);
                                String id=jsonObject.getString("id");
                                String name=jsonObject.getString("name");
                                String price=jsonObject.getString("price");
                                String advance_time=jsonObject.getString("time");
                                String descript=jsonObject.getString("descript");
                                AdvancePullDTO advancePullDTO = new AdvancePullDTO();
                                advancePullDTO.setAdvance_form_id(uuid);
                                advancePullDTO.setAdvancetypess_id(id);
                                advancePullDTO.setAdvancetypess_name(name);
                                advancePullDTO.setAdvancetypess_price(price);
                                advancePullDTO.setAdvance_time(advance_time);
                                advancePullDTO.setAdvance_desciption(descript);
                                advanceResource.addAdvanceInfo(advancePullDTO);
                            }
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }


                //日志操作
                OperatorLogPullDTO operatorlogPullDTO=new OperatorLogPullDTO();
                operatorlogPullDTO.setWork_form_id(uuid);
                operatorlogPullDTO.setOperator_log_type("预支费用申请");
                operatorlogPullDTO.setOperator_log_title(advance_form_number);
                operatorlogPullDTO.setOperator_log_content(advance_form_reason);
                operatorlogPullDTO.setMember_id(member_id);
                operatorLogResource.addOperatorLogInfo(operatorlogPullDTO);

                //流程上报

                WorkFlowPullDTO workFlowPullDTO=new WorkFlowPullDTO();
                workFlowPullDTO.setWork_flow_formid(uuid);
                workFlowPullDTO.setWork_flow_type("advance_form");
                workFlowPullDTO.setWork_flow_desc("预支费用申请请求审批");
                workFlowPullDTO.setWork_flow_date(advance_form_time);
                workFlowPullDTO.setWork_flow_order("0");
                workFlowPullDTO.setWork_flow_createid(member_id);
                workFlowPullDTO.setWork_flow_approval(advanceFormPullDTO.getReport_people());
                workFlowPullDTO.setWork_flow_approval_organization_id(advanceFormPullDTO.getWork_flow_approval_organization_id());
                workFlowPullDTO.setFlow_path_id(advanceFormPullDTO.getFlow_path_id());
                workFlowPullDTO.setWork_flow_suggestion("");
                workFlowResource.addWorkFlowInfo(workFlowPullDTO);


        }else{

            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.add_fail);
        }

        return resultDTO;
    }

    /**
     * 修改方法
     * @param dataDTO
     * @return
     */
    @Override
    public ResultDTO updateAdvanceFormInfo(AdvanceFormPullDTO dataDTO) {

        /**
         * 先删除类别表
         *
         * 再进行添加
         */
        ResultDTO resultss = null;
        String advance_form_id = dataDTO.getAdvance_form_id();
        AdvancePullDTO advancePullDTO=new AdvancePullDTO();
        advancePullDTO.setAdvance_form_id(advance_form_id);
        advanceResource.deleteAdvanceInfo(advancePullDTO);
        //  if(resultss!=null){
        if (null != dataDTO.getAdvancetype() && !"".equals(dataDTO.getAdvancetype())) {
            String financetype = dataDTO.getAdvancetype();
            try {
                JSONArray array = new JSONArray(financetype);
                if (array != null && array.length() > 0) {
                    List<AdvanceFormPullDTO> result = new ArrayList<AdvanceFormPullDTO>();
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject jsonObject = array.getJSONObject(i);
                        String id = jsonObject.getString("id");
                        String name = jsonObject.getString("name");
                        String number = jsonObject.getString("descript");
                        String price = jsonObject.getString("price");
                        String time = jsonObject.getString("time");
                        AdvancePullDTO advancePullDTO1 = new AdvancePullDTO();
                        advancePullDTO1.setAdvance_form_id(dataDTO.getAdvance_form_id());
                        advancePullDTO1.setAdvancetypess_id(id);
                        advancePullDTO1.setAdvancetypess_name(name);
                        advancePullDTO1.setAdvance_desciption(number);
                        advancePullDTO1.setAdvancetypess_price(price);
                        advancePullDTO1.setAdvance_time(time);
                        advanceResource.addAdvanceInfo(advancePullDTO1);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        ResultDTO resultDTO = new ResultDTO();

        String QUERY = "";

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //更新sql语句
        QUERY += "update advance_form set advance_form_time ='"  + df.format(new Date()) + "'";
        if(null!=dataDTO.getAdvance_form_reason()&&!"".equals(dataDTO.getAdvance_form_reason())){
            QUERY += ",advance_form_reason = '" + dataDTO.getAdvance_form_reason() + "'";
        }

        if(null!=dataDTO.getAdvance_form_number()&&!"".equals(dataDTO.getAdvance_form_number())){
            QUERY += ",advance_form_number ='" + dataDTO.getAdvance_form_number() + "'";
        }
        if(null!=dataDTO.getIsverify()&&!"".equals(dataDTO.getIsverify())){
            QUERY += ",isverify ='" + dataDTO.getIsverify() + "'";
        }

        if(null!=dataDTO.getAdvance_form_bignumber()&&!"".equals(dataDTO.getAdvance_form_bignumber())){
            QUERY += ",advance_form_bignumber ='" + dataDTO.getAdvance_form_bignumber() + "'";
        }

        if(null!=dataDTO.getFail_resource()&&!"".equals(dataDTO.getFail_resource())){
            QUERY += ",fail_resource ='" + dataDTO.getFail_resource() + "'";
        }

//        if(null!=dataDTO.companyfax&&!"".equals(dataDTO.companyfax)){
//            QUERY += ",company_fax ='" + dataDTO.getCompanyfax() + "'";
//        }
//
//        if(null!=dataDTO.companyurl&&!"".equals(dataDTO.companyurl)){
//            QUERY += ",company_url ='" + dataDTO.getCompanyurl() + "'";
//        }
//
//        if(null!=dataDTO.picurl&&!"".equals(dataDTO.picurl)){
//            QUERY += ",pic_url ='" + dataDTO.getPicurl() + "'";
//        }
//
//        if(null!=dataDTO.yuliu&&!"".equals(dataDTO.yuliu)){
//            QUERY += ",yuliu ='" + dataDTO.getYuliu() + "'";
//        }

        QUERY += " where advance_form_id = '" + dataDTO.getAdvance_form_id() + "'";


        int result = this.addReportingTo(QUERY);

        // 判断SQl是否执行成功
        if (result != 0) {

            resultDTO.setStr(advance_form_id);
            WorkFlowPullDTO workFlowPullDTO=new WorkFlowPullDTO();
            workFlowPullDTO.setWork_flow_formid(dataDTO.getAdvance_form_id());
            workFlowPullDTO.setWork_flow_approval(dataDTO.getReport_people());
            workFlowPullDTO.setWork_flow_approval_organization_id(dataDTO.getWork_flow_approval_organization_id());
//            workFlowPullDTO.setWork_flow_order("0");
            workFlowPullDTO.setIsverify("0");
            workFlowResource.updateWorkFlowInfo(workFlowPullDTO);



            resultDTO.setStatus("90000");//
            resultDTO.setDescritpion(warnSrc.update_success);
        } else {
            resultDTO.setStatus("90001");//
            resultDTO.setDescritpion(warnSrc.update_fail);
        }
        return resultDTO;
    }




    //根据主键删除
    @Override
    public ResultDTO deleteAdvanceFormInfo(AdvanceFormPullDTO advanceFormPullDTO) {


        //删除之前首先查询该表中是否有记录

        String sql="select count(1) from advance_form WHERE advance_form_id='"+advanceFormPullDTO.getAdvance_form_id()+"'";
        String existadvance= getReportingToOne(sql);

        int result = 0;

        ResultDTO resultDTO = new ResultDTO();
        // 删除SQL语句
        if(!existadvance.equals("0")){
            String QUERY = "";
            QUERY += "delete from advance_form where advance_form_id = '"+advanceFormPullDTO.getAdvance_form_id()+"'";

             result = this.addReportingTo(QUERY);
        }

        // 判断SQl是否执行成功
        if (result!= 0) {

            resultDTO.setStatus("90000");
            resultDTO.setDescritpion(warnSrc.delete_success);

            AdvancePullDTO advancePullDTO = new AdvancePullDTO();
            advancePullDTO.setAdvance_form_id(advanceFormPullDTO.getAdvance_form_id());
            advanceResource.deleteAdvanceInfo(advancePullDTO);


            WorkFlowPullDTO workFlowPullDTO=new WorkFlowPullDTO();
            workFlowPullDTO.setWork_flow_formid(advanceFormPullDTO.getAdvance_form_id());
            workFlowResource.deleteWorkFlowInfo(workFlowPullDTO);


        } else {
            resultDTO.setStatus("90001");
            resultDTO.setDescritpion(warnSrc.delete_fail);
        }
        return resultDTO;
    }

}
